import type { CreateReadingQuestion } from '@/types'
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import message from '@/components/common/message'
import { createOrUpdateReadingQuestionGroup, getReadingQuestionGroupDetail } from '@/request/teacher/bank'
import { useTeacherStore } from '@/store/teacher'

export interface ArticleContent {
  title: string
  author: string
  content: string
}

export interface QuestionGroupSettings {
  title: string
  extracurricularType: string
  textbookType: string
  correspondingGrade: string
  estimatedTime: number
  difficulty: number
  textType: string
  inClass: number
}

export function useQuestionGroup(questionGroupId?: string) {
  // 题目相关状态
  const editingQuestion = ref<CreateReadingQuestion>()
  const isCreateQuestionPopupVisible = ref(false)
  const articleTitle = ref('')
  const articleContent = ref('')
  const articleAuthor = ref('')

  // 题组设置状态
  const questionList = ref<CreateReadingQuestion[]>([])
  const questionGroupSettings = ref<QuestionGroupSettings>({
    title: '',
    extracurricularType: '',
    textbookType: '',
    correspondingGrade: '一年级',
    estimatedTime: 60,
    difficulty: 1,
    textType: '阅读',
    inClass: 0,
  })
  // 加载已有题组数据
  if (questionGroupId) {
    getReadingQuestionGroupDetail({ readingId: questionGroupId })
      .then((data) => {
        questionList.value = data.entry.questions.map(question => ({
          type: question.type,
          title: question.title,
          description: question.description,
          correctAnswer: question.correctAnswer,
          analysis: question.analysis,
          options: question.options
            ? question.options.map(i => ({
                label: i.optionLabel,
                value: i.optionText,
              }))
            : [],
        }))
        questionGroupSettings.value = {
          title: data.entry.title,
          extracurricularType: data.entry.extracurricularType || '',
          textbookType: data.entry.textbookType || '',
          correspondingGrade: data.entry.correspondingGrade,
          estimatedTime: data.entry.estimatedTime,
          difficulty: data.entry.difficulty,
          textType: data.entry.textType || '',
          inClass: data.entry.inClass,
        }
        articleTitle.value = data.entry.title
        articleContent.value = data.entry.description
        articleAuthor.value = data.entry.author
      })
  }
  else {
    const route = useRoute()
    questionGroupSettings.value.inClass = Number(route.query.inClass) || 0
  }

  // 计算属性
  const hasQuestions = computed(() => questionList.value.length > 0)
  const canSave = computed(() => hasQuestions.value && questionGroupSettings.value.title.trim() !== '')

  // 题目管理方法
  function handleOpenCreateQuestion() {
    editingQuestion.value = undefined
    isCreateQuestionPopupVisible.value = true
  }

  function handleOpenEditQuestion(question: CreateReadingQuestion) {
    editingQuestion.value = question
    isCreateQuestionPopupVisible.value = true
  }

  function handleCreateQuestion(question: CreateReadingQuestion, editingIndex: number) {
    if (editingIndex !== -1) {
      questionList.value.splice(editingIndex, 1, question)
    }
    else {
      questionList.value.push(question)
    }
    isCreateQuestionPopupVisible.value = false
  }

  function handleCloseCreateQuestionPopup() {
    isCreateQuestionPopupVisible.value = false
  }

  function removeQuestion(index: number) {
    questionList.value.splice(index, 1)
  }

  function moveQuestionUp(index: number) {
    if (index === 0)
      return
    const question = questionList.value.splice(index, 1)[0]
    questionList.value.splice(index - 1, 0, question)
  }

  function moveQuestionDown(index: number) {
    if (index === questionList.value.length - 1)
      return
    const question = questionList.value.splice(index, 1)[0]
    questionList.value.splice(index + 1, 0, question)
  }

  function getEditingIndex() {
    return questionList.value.findIndex(i => i === editingQuestion.value)
  }

  // 保存题组
  async function saveQuestionGroup(articleContent: ArticleContent, justReturnData = false) {
    const { teacher } = useTeacherStore()

    try {
      const data = {
        author: articleContent.author, // 文章作者
        correspondingGrade: questionGroupSettings.value.correspondingGrade,
        createdBy: questionGroupId ? undefined : teacher.teacherId,
        description: articleContent.content, // 文章内容
        difficulty: questionGroupSettings.value.difficulty,
        estimatedTime: questionGroupSettings.value.estimatedTime,
        extracurricularType: questionGroupSettings.value.extracurricularType || undefined,
        inClass: questionGroupSettings.value.inClass,
        questions: questionList.value.map((question, index) => ({
          analysis: question.analysis,
          correctAnswer: question.correctAnswer,
          options: question.options.map(i => ({
            label: i.label,
            text: i.value,
          })),
          orderIndex: index,
          questionDescription: question.description,
          questionTitle: question.title,
          type: question.type,
        })),
        readingId: questionGroupId || undefined, // 传id是编辑，不传是新建
        textbookType: questionGroupSettings.value.textbookType || undefined,
        textType: questionGroupSettings.value.textType || undefined,
        title: questionGroupSettings.value.title, // 题组标题
      }
      if (justReturnData)
        return data
      await createOrUpdateReadingQuestionGroup(data)

      message.success('保存成功')
      return data
    }
    catch (error) {
      console.error('保存失败:', error)
      message.error('保存失败')
    }
  }

  // 重置状态
  function resetState() {
    questionList.value = []
    editingQuestion.value = undefined
    isCreateQuestionPopupVisible.value = false
    questionGroupSettings.value = {
      title: '',
      extracurricularType: '校本',
      textbookType: '',
      correspondingGrade: '一年级',
      estimatedTime: 60,
      difficulty: 1,
      textType: '阅读',
      inClass: 0,
    }
  }

  return {
    // 状态
    questionList,
    editingQuestion,
    isCreateQuestionPopupVisible,
    questionGroupSettings,

    // 计算属性
    hasQuestions,
    canSave,

    // 题目管理方法
    handleOpenCreateQuestion,
    handleOpenEditQuestion,
    handleCreateQuestion,
    handleCloseCreateQuestionPopup,
    removeQuestion,
    moveQuestionUp,
    moveQuestionDown,
    getEditingIndex,

    // 保存和重置
    saveQuestionGroup,
    resetState,

    // 其它信息（文章内容、作者）
    articleTitle,
    articleContent,
    articleAuthor,
  }
}
